<template>
  <div class="home">
    <div class="home_content" id="chatContainer">
      <template v-for="(item, index) in defaultList" :key="index">
        <message-item :role="item.role" :message="item.content"></message-item>
      </template>
      <template v-for="(item, index) in messageList" :key="index">
        <message-item :role="item.role" :message="item.content"></message-item>
      </template>

      <message-item role="assistant" :message="currentAssistantMessage"
        v-if="currentAssistantMessage != ''"></message-item>

    </div>
    <div class="home-box" v-if="loading">
      <el-button type="primary" plain class="home-loading">AI正在思考中...</el-button>
    </div>

    <div class="home-box" v-else>
      <el-input v-model="messageText" placeholder="请输入..." @focus="inputFocus" @keyup.enter="message" />
      <el-button type="primary" @click="message" class="message-button">
        <svg t="1678429975200" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
          p-id="2913" width="2em" height="2em">
          <path
            d="M717.2 870c-10.1 0-20.2-3-29-8.8L493 731.6c-11.7-7.8-14.9-23.6-7.1-35.2 7.8-11.8 23.5-14.8 35.2-7.1L716.3 819l86-677.3L209 479.1l184.1 125.1c11.7 7.8 14.9 23.6 7.1 35.2-7.8 11.8-23.5 14.8-35.2 7.1L180.8 524.2c-15.2-10.1-24-27-23.4-45.4 0.6-18.3 10.4-34.7 26.3-43.8L774.6 95.8c17.4-9.9 38.5-9.2 55.2 1.8 16.6 11.1 25.5 30.3 23 50.1L769.3 824c-2.3 18.2-13.5 33.6-30.2 41.3-7 3.1-14.5 4.7-21.9 4.7z"
            fill="#ffffff" p-id="2914"></path>
          <path
            d="M381.6 870c-14 0-25.4-11.4-25.4-25.4V727.3l433-607.3c8.2-11.4 24.1-14 35.4-6 11.4 8.1 14.1 24 6 35.4L407 743.6v101c0 14-11.4 25.4-25.4 25.4z"
            fill="#ffffff" p-id="2915"></path>
        </svg></el-button>
    </div>
  </div>
</template>
<script lang="ts" setup  name="Index">
import MessageItem from '@/components/MessageItem'
import { ref } from 'vue'
const messageText = ref('')  // 当时输入的值
const messageList = ref([]) //所有聊天数据
const messageListNew = ref([]) //最近10条聊天数据
const loading = ref(false) // loading
const defaultList = ref([{
  role: 'system',
  content: `龙宝智能AI为您服务：

1、 知乎百度答题、作业题目

2、写文案、写论文，写小说、写脚本

3、文案润色、翻译、写诗作词

4、扮演面试官、扮演书籍电影角色

5、倾诉、解忧、讲故事......

---------------
例1：写一篇工作日报我是行政

例2：把下文翻译成英文：xxx

例3：写一出能活的短视频剧本

---------------

或者可以问我其他问题   

越完整的描述，我越精确哟!`,
}]) //默认显示聊天

const currentAssistantMessage = ref('') // 当前回答返回的数据

// 滚动到页面底部
const scrollToBottom = () => {
  // window.scrollTo({
  //   top: document.documentElement.offsetHeight,
  //   left: 0,
  //   behavior: "smooth",
  // });
  var chatContainer = document.getElementById('chatContainer');
  chatContainer.scrollTop = chatContainer.scrollHeight;
};

const inputFocus = () => {
  scrollToBottom()
}
const message = async () => {
  if (!messageText.value) {
    return
  }
  loading.value = true
  messageList.value = [
    ...messageList.value,
    {
      role: 'user',
      content: messageText.value,
    },
  ]
  scrollToBottom()

  console.log(messageText.value, 'messageText')
  const decoder = new TextDecoder('utf-8');
  if (messageList.value.length >= 21) {
    // 当前已结回复了10条数据
    messageListNew.value = messageList.value.slice(2)
  } else {
    messageListNew.value = messageList.value
  }
  //http://192.168.100.160:20000/v1/chat/completions
  //http://192.168.100.160:11434/api/chat
  fetch('/v1/chat/completions', {
    headers: {
      'Content-Type': 'application/json'
    },
    method: 'POST',
    body: JSON.stringify({
      model: "glm4-chat",
      messages: messageListNew.value,
      temperature: 0.6,
      stream: true
    })
  }).then(response => {
    // 获取 reader
    const reader = response.body.getReader();
    // 读取数据
    return reader.read().then(function process({ done, value }) {
      if (done) {
        console.log('Stream finished');
        loading.value = false
        messageList.value = [
          ...messageList.value,
          {
            role: 'assistant',
            content: currentAssistantMessage.value,
          },
        ]
        messageText.value = ''
        currentAssistantMessage.value = ''
        scrollToBottom()
        return;
      }

      if (value) {
        // 解码数据
        let text = decoder.decode(value);
        console.log('回复', text);
        if (text.includes('data:')) {
          // 移除 'data: [DONE]' 标记
          if (text.includes('data: [DONE]')) {
            text = text.trim().substring(0, -12);
          }
          // 替换 'data:' 并转换为数组格式
          text = `[${text.replace(/data:/g, ',').slice(1)}]`;
          try {
            const json = JSON.parse(text);
            for (const item of json) {
              const data = item.choices[0].delta?.content || '';
              scrollToBottom();
              currentAssistantMessage.value += data;
            }
          } catch (error) {
            console.error('JSON 解析错误:', error);
          }
        }
        // 读取下一段数据
        return reader.read().then(process);
      }
    });
  })
    .catch((error) => {
      console.log(error);
      loading.value = false
    });
}
</script>

<style scoped lang="scss">
.home {
  height: 100%;
  padding: 20px 0 90px 0;
  position: relative;
}

.home_content {
  padding-bottom: 5px;
  position: relative;
  width: 100%;
  height: 100%;
  padding: 0 15px;
  overflow-y: auto
}

.home-box {
  position: absolute;
  height: 80px;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 16px 20px;
  border-top: 1px solid #eee;
  box-shadow: 0px 0px 0.667vw 0.4vw rgba(0, 0, 0, 0.05);
  background: #fff;

  .el-input {
    height: 48px;
    flex: 1;
    font-size: 16px;
  }

  .message-button {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    margin-left: 10px;
  }

  .home-loading {
    width: 100%;
    height: 48px;
  }
}
</style>
